//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by cc on 9/21/17.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 通过 WebView 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {

    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
        
        //取消webView的Scroll滚动视图  -- 新浪微博的服务器，返回的授权页面默认就是手机全屏
        webView.scrollView.isScrollEnabled = false
        
        //设置代理
        webView.delegate = self
        
        
        //設置導航欄
        title = "登录新浪微博"
        //導航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回",target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoField))
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectUrl)"

        //1.URL 确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        
        //2.建立请求
        let request = URLRequest(url: url)
        
        //3.加载请求
        webView.loadRequest(request)
        
        
        
    }
    
    
    //MARK : - 监听方法
    //关闭控制器
    @objc private func close() {
        //关闭HUD
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    
    
    /// 自动填充 -webView 注入
    // 点击登录按钮， 执行 submit() 将本地数据提交到服务器
    @objc private func autoField() {
        //准备js
        let js = "document.getElementById('userId').value= '13710320761';" + "document.getElementById('passwd').value= 'luoweishuan120';"
        //让webView执行 js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    
    
}


extension WBOAuthViewController: UIWebViewDelegate {

    /// webView将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求类型
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //1.如果请求地址包含 http://misters.cc 不加载页面，否则加载
        // request.url?.absoluteString.hasPrefix(WBRedirectUrl)返回的是可选项 true/false/nil
        if request.url?.absoluteString.hasPrefix(WBRedirectUrl) == false {
            return true
        }
        
        //print("加载request  ----\(String(describing: request.url?.absoluteString)) -- ")
        //print("加载请求 ---  \(request.url?.query ?? "")")
        
        
        //2.从 http://misters.cc 回调地址的查询字符串中查找 `code=`
        // 如果有，授权成功，否则失败
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        //3. 从 query 字符串中取出授权码
        //代码走到这，url中一定有查询字符串，并且包含 `code=`
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码...\(code)")
        
        
        //4.使用授权码获取AccessToken
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "網絡請求失敗")
            } else {
                SVProgressHUD.showInfo(withStatus: "登錄成功")
                
                //跳轉界面， 通過通知發送登錄成功消息
                //1>發送通知  -- 不關心有沒有監聽者
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification), object: nil)
                
                //2>關閉窗口
                self.close()
                
            }
            
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}



















